jQuery(function() {
	
	//添加二期配置弹窗
	jQuery(".addOtherERBtn").on("click", function() {
		//saveForeignQuote(3);
		//jQuery(".btn").attr("disabled", true);
		jQuery("#queryOtherERModal").modal('show');
	});
	var serverotherERData = {};
	var serverotherERTable;
	jQuery(document).ready(function(){
		serverotherERTable = jQuery('#otherERTable').DataTable({
			"serverSide" : true,
			"ordering" : false,
			"ajax" : {
				"dataType" : "json",
				"type" : "get",
				"cache" : false,
				"url" : window.rootPath+ '/ui/configdetailfor/getpage',
				"data" : function(d) {
					return $.extend({}, d,serverotherERData);
						}
					},
				columns : [
				           {
				        	   data:null,
				        	   defaultContent : "" 
				           },
				           {
				        	   data : null,
				        	   defaultContent : "",
				        	   render : function(data,type, full, meta) {
							      var id = data.id
								  var operate = '<input type="checkbox" class="checkchild">';
								  return operate;
									}
							},
				           {
								data : 'cContractNumber'
							},
							{
								data : 'cProductPlanNumber'
							},
							{
								data : 'cConfigurationType'
							},
							{
								data : 'cOrderNumber'
							},
							{
								data : 'cPartPicNumDes'
							},
							{
								data : 'cPartName'
							},
							{
								data : 'cMaterial'
							},
				           {
				        	   data : 'nTotalCount'
				           }
							],
				"drawCallback" : function(oSettings) {
						var k = 0;
						var total = oSettings.aiDisplay.length+ oSettings._iDisplayStart;
						for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
							$('td:eq(0)',oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
									k++;
								}

							}
						});
	});

	var serverData2 = {};
	var serverTable2;
	serverData2.quoteId = jQuery("#id").val();
	jQuery(document).ready(function() {
		serverTable2 = jQuery('#otherERCRMTable').DataTable({
				"serverSide" : true,
				"ordering" : false,
				"ajax" : {
				"dataType" : "json",
				"type" : "get",
				"cache" : false,
				"url" : window.rootPath+'/ui/quote-foreign/getOtherpageER',
				"data" : function(d) {
						return $.extend({}, d,serverData2);
										}
						},
				columns : [
				           {
				        	   data : null,
							   defaultContent : "" 
				           },
				           {
				        	   data : null,
				        	   defaultContent : "",
				        	   render : function(data,type, full, meta) {
										var id = data.id
										var operate = '<input type="checkbox" class="checkchild1">';
										return operate;
											}
							}, 
							{
			                    data: 'deviceName',
								render:function(data,type,full,meta){
									return '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>';
									//return "<div title='"+data+"' style='overflow:hidden; text-overflow:ellipsis; white-space:nowrap;'>"+data+"</div>"
								}
			                },
			                {
			                    data: 'type',
								render:function(data,type,full,meta){
									return '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>';
									//return "<div title='"+data+"' style='overflow:hidden; text-overflow:ellipsis; white-space:nowrap;'>"+data+"</div>"
								}
			                },
			                {
			                	data: 'material',
								render:function(data,type,full,meta){
									return '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>';
									//return "<div title='"+data+"' style='overflow:hidden; text-overflow:ellipsis; white-space:nowrap;'>"+data+"</div>"
								}
			                },
			                {
			                    data: 'unit'
			                },
			                {
			                	data: 'amount'
			                },
			                {
			                	data: 'costPrice'
			                },
			                {
			                	data: 'price'
			                }
							],
				"drawCallback" : function(oSettings) {
							  var k = 0;
							  var total = oSettings.aiDisplay.length+ oSettings._iDisplayStart;
							for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
							    $('td:eq(0)',oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
										k++;
											}
										}
									});

				});

	//添加二期配置弹窗
	jQuery(".choiceBtn").on("click", function() {
		var selects = getSelect("#otherERTable", 1);
		if(selects.length==0){
		       $.springLemonDialog({
		         content: '请选择记录',// 确认文本
		         clickButton: function (sender, modal, index) {// 按钮事件处理
		             $(this).closeDialog(modal);
		         }
		       }); 
		   }else{
			   var ids=selects[0].id;
			   for(var i=1;i<selects.length;i++){
				   ids += ',' + selects[i].id;  
			   }
			 var url=window.rootPath+"/ui/configdetailfor/saveOtherERquoteFor"+"?ids="+ids+"&quoteId="+jQuery("#id").val();
			   $.springLemonDialog({
			         content: '确认选择'+selects.length+'条记录？',// 确认文本
			         clickButton: function (sender, modal, index) {// 按钮事件处理
			        	 if (index == 0) {
			        		jQuery(".btn").attr("disabled", true);
			        		 jQuery.ajax({
			        			    url:encodeURI(url),
			        	            cache:false,
			        	            type :"get",
			        	            dataType:"json",
			        	            contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
			        	            success:function(data){
			        	            	serverData2.quoteId = jQuery("#id").val();
			        	            	serverTable.draw(false); 
			        	            	serverTable1.draw(); 
			        	            	serverTable2.draw(); 
			        	            	productSum();
			        	            	jQuery(".btn").attr("disabled", false);
			        	            }
			        	        });	
			        	 }
			             $(this).closeDialog(modal);
			         }
			       });  
		   }
	});


	////二期上查询
	jQuery('.searchotherERBtn').on('click', function() {
		 serverotherERData.cContractNumber = jQuery('#cContractNumber').val();
		 serverotherERData.key = jQuery('#otherERkeyword').val();
		 serverotherERTable.draw();
	})
	jQuery('.resetotherERBtn').on("click", function() {
		 jQuery('#cContractNumber').val('');
		 jQuery('#otherERkeyword').val('');
		 serverotherERData.cContractNumber = '';
		 serverotherERData.key = '';
		 serverotherERTable.draw();
	});

	////二期下查询
	jQuery('.searchotherERCRMBtn').on('click', function() {
		 serverData2.key = jQuery('#otherERCRMkeyword').val();
		 serverTable1.draw();
		 serverTable2.draw();
	})
	jQuery('.resetotherERCRMBtn').on("click", function() {
		 jQuery('#otherERCRMkeyword').val('');
		 serverData2.key = '';
		 serverTable1.draw();
		 serverTable2.draw();
	});
	jQuery('.editotherERCRMBtn').on("click", function() {
		var selects = getSelect("#otherERCRMTable", 1);
		if (selects.length > 1) {
			$.springLemonDialog({
				content : '一次只能编辑一条记录',// 确认文本
				clickButton : function(sender, modal, index) {// 按钮事件处理
					$(this).closeDialog(modal);
				}
			});
		} else if (selects.length == 0) {
			$.springLemonDialog({
				content : '请选择要编辑的记录',// 确认文本
				clickButton : function(sender, modal, index) {// 按钮事件处理
					$(this).closeDialog(modal);
				}
			});
		} else if (selects.length == 1) {
			 var id=selects[0].id;
		 	    jQuery("#otherId").val(id);
	 		 jQuery("#othercreateTime").val(selects[0].createTime);
	 		 jQuery("#deviceName").val(selects[0].deviceName);
	         jQuery("#type").val(selects[0].type);
	         jQuery("#material").val(selects[0].material);
	         jQuery("#unit").val(selects[0].unit);
	         jQuery("#amount").val(selects[0].amount);
	         jQuery("#price").val(selects[0].price);
	         jQuery("#replacePrice").val(selects[0].costPrice);
	         jQuery("#otherDeviceModal").modal("show");
		}
	});

	jQuery('.delotherERCRMBtn').on("click", function() {
		var selects=getSelect("#otherERCRMTable",1);
		if(selects.length==0){
		       $.springLemonDialog({
		         content: '请选择删除的记录',// 确认文本
		         clickButton: function (sender, modal, index) {// 按钮事件处理
		             $(this).closeDialog(modal);
		         }
		       }); 
		   }else{
			   var ids=selects[0].id;
			   for(var i=1;i<selects.length;i++){
				   ids += ',' + selects[i].id;  
			   }
			 var url=window.rootPath+"/ui/quote-foreign/delOtherDevice"+"?ids="+ids;
			   $.springLemonDialog({
			         content: '确认删除'+selects.length+'条记录？',// 确认文本
			         clickButton: function (sender, modal, index) {// 按钮事件处理
			        	 if (index == 0) {
			        		jQuery(".btn").attr("disabled", true);
			        		 jQuery.ajax({
			        			    url:encodeURI(url),
			        	            cache:false,
			        	            type :"get",
			        	            dataType:"json",
			        	            contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
			        	            success:function(data){
			        	            	serverTable1.draw(false); 
			        	            	serverTable2.draw(false); 
			        	            	productSum();
			        	            	jQuery(".btn").attr("disabled", false);
			        	            }
			        	        });	
			        	 }
			             $(this).closeDialog(modal);
			         }
			       });  
		   }
	});

	jQuery('.searchotherERCRMBtn').on("click", function() {
		var selects=getSelect("#otherERCRMTable",1);
		if(selects.length==0){
		       $.springLemonDialog({
		         content: '请选择查询数据',// 确认文本
		         clickButton: function (sender, modal, index) {// 按钮事件处理
		             $(this).closeDialog(modal);
		         }
		       }); 
		   }else if(selects.length>1){
			   $.springLemonDialog({
			         content: '只能查询一条数据',// 确认文本
			         clickButton: function (sender, modal, index) {// 按钮事件处理
			             $(this).closeDialog(modal);
			         }
			       }); 
		   }else {
			 //var url=window.rootPath+"/ui/quote/delOtherDevice"+"?ids="+ids;
			 //jQuery("#typekeyword").val(selects[0].type);
			   var id=selects[0].id;
			   jQuery("#otherId1").val(id);
		 		 jQuery("#othercreateTime1").val(selects[0].createTime);
		 		 jQuery("#deviceName1").val(selects[0].deviceName);
		         jQuery("#type1").val(selects[0].type);
		         jQuery("#material1").val(selects[0].material);
		         jQuery("#unit1").val(selects[0].unit);
		         jQuery("#amount1").val(selects[0].amount);
		         jQuery("#price1").val(selects[0].price);
		         jQuery("#replacePrice1").val(selects[0].costPrice);
			 jQuery("#typekeyword").val(selects[0].type);
			 serverData3.type = selects[0].type;
			 jQuery("#deviceNamekeyword").val(selects[0].deviceName);
			 serverData3.deviceName = selects[0].deviceName;
			 jQuery("#materialkeyword").val(selects[0].material);
			 serverData3.material = selects[0].material;
			 serverTable3.draw();
			 jQuery("#queryOtherERPriceModal").modal("show");
		   }
	});
	jQuery('#pull-in-otherreplacePrice').on("click", function() {
		var selects=getSelect("#otherreplacePriceTable",1);
		if(selects.length==0){
			$.springLemonDialog({
				content: '请选择要引入的数据',// 确认文本
				clickButton: function (sender, modal, index) {// 按钮事件处理
					$(this).closeDialog(modal);
				}
			}); 
		}else if(selects.length>1){
			$.springLemonDialog({
				content: '只能选择一条数据',// 确认文本
				clickButton: function (sender, modal, index) {// 按钮事件处理
					$(this).closeDialog(modal);
				}
			}); 
		}else if(selects.length==1){
			jQuery("#typekeyword").val("");
			jQuery("#deviceNamekeyword").val("");
			jQuery("#materialkeyword").val("");
			
			var url2=window.rootPath+'/ui/quote-foreign/saveOtherDevice';
			var quoteId = jQuery("#id").val();
			var otherId = jQuery("#otherId1").val();
			var deviceName = selects[0].deviceName;
			var type = selects[0].type;
			var material = selects[0].material;
			var unit = selects[0].unit;
			var amount = selects[0].amount;
			var price = selects[0].price;
			var replacePrice = selects[0].costPrice;
			var createTime=jQuery("#othercreateTime1").val();
			
			var d = {
				    "id":otherId,
				    "createTime":createTime,
				    "deviceName": deviceName,
	                "type": type,
	                "material": material,
	                "unit": unit,
	                "amount": amount,
	                "price": price,
	                "costPrice": replacePrice,
	   	            "quote": {
	   	                "id": quoteId
	   	            } 
	   	        };
			jQuery(".btn").attr("disabled", true);
			jQuery.ajax({
		          type: 'post',
		          url: encodeURI(url2),
		          data: JSON.stringify(d),
		          dataType: 'json',
		          contentType: 'application/json;charset=utf-8',
		          success: function (data) {
		        	  	productSum();
		        	  	serverTable1.draw();
		        	  	serverTable2.draw();
		        		jQuery('#queryOtherERPriceModal').modal('hide');
		        		jQuery(".btn").attr("disabled", false);
		          }
	    	  	});
		}
	});

	var serverData3 = {};
	var serverTable3;
	jQuery(document).ready(function() {
		serverTable3 = jQuery('#otherreplacePriceTable').DataTable({
				"serverSide" : true,
				"ordering" : false,
				"ajax" : {
				"dataType" : "json",
				"type" : "get",
				"cache" : false,
				"url" : window.rootPath+'/ui/quote-foreign/getOtherpageprice',
				"data" : function(d) {
						return $.extend({}, d,serverData3);
										}
						},
				columns : [
				           {
				        	   data : null,
							   defaultContent : "" 
				           },
				           {
				        	   data : null,
				        	   defaultContent : "",
				        	   render : function(data,type, full, meta) {
										var id = data.id
										var operate = '<input type="checkbox" class="checkchild1">';
										return operate;
											}
							}, 
							{
			                    data: 'deviceName',
								render:function(data,type,full,meta){
									return '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>';
									//return "<div title='"+data+"' style='overflow:hidden; text-overflow:ellipsis; white-space:nowrap;'>"+data+"</div>"
								}
			                },
			                {
			                    data: 'type',
								render:function(data,type,full,meta){
									return '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>';
									//return "<div title='"+data+"' style='overflow:hidden; text-overflow:ellipsis; white-space:nowrap;'>"+data+"</div>"
								}
			                },
			                {
			                	data: 'material',
								render:function(data,type,full,meta){
									return '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>';
									//return "<div title='"+data+"' style='overflow:hidden; text-overflow:ellipsis; white-space:nowrap;'>"+data+"</div>"
								}
			                },
			                {
			                    data: 'unit'
			                },
			                {
			                	data: 'amount'
			                },
			                {
			                	data: 'costPrice'
			                },
			                {
			                	data: 'price'
			                }
							],
				"drawCallback" : function(oSettings) {
							  var k = 0;
							  var total = oSettings.aiDisplay.length+ oSettings._iDisplayStart;
							for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
							    $('td:eq(0)',oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
										k++;
											}
										}
									});

				});

	
	// 引入客户信息弹窗
	jQuery('#queryCustomer').on("click", function() {
		showCustomer();// 显示客户信息
	});
	jQuery('#pull-customer-in').on('click', function() {
		var selects = getSelect("#query-customer-table", 1);
		if (selects.length > 1) {
			message("只能引入一条客户");
		} else if (selects.length == 0) {
			message("没有选中客户");
		} else if (selects.length == 1) {
			jQuery("#customerId").val(selects[0].id);
			jQuery("#customerName").val(selects[0].customerName);
			jQuery("#query-Customer-Modal").modal('hide');
		}

	});

	// ///////////////// 泵 ///////////////////////
	// 泵table
	var serverData = {};
	serverData.quoteForeignId = jQuery("#id").val();
	var serverTable;
	jQuery(document)
			.ready(
					function() {
						serverTable = jQuery('#mainDeviceTable')
								.DataTable(
										{
											"serverSide" : true,
											"ordering" : false,
											"ajax" : {
												"dataType" : "json",
												"type" : "get",
												"cache" : false,
												"url" : window.rootPath
														+ '/ui/quote-foreign/getMainpage',
												"data" : function(d) {
													return $.extend({}, d,
															serverData);
												}
											},
											columns : [
													{
														data : null,
														defaultContent : ""
													},
													{
														data : null,
														defaultContent : "",
														render : function(data,
																type, full,
																meta) {
															var id = data.id
															var operate = '<input type="checkbox" class="checkchild">';
															return operate;

														}
													},
													{
														data : 'productName'
													},
													{
														data : 'productType'
													},
													{
														data : 'productModel'
													},
													{
														data : null,
														render : function(data,
																type, full,
																meta) {
															var dOut;
															if (data.isInventory == "1") {
																dOut = '<td class="center" ><span class="badge label-pill label-primary">降库产品</span></td>';
															} else if (data.isInventory == "2"){
																dOut = '<td class="center" ><span class="badge label-pill label-success">被降库</span></td>';
															}else{
																dOut = '<td class="center" ><span class="badge label-pill label-danger">未降库</span></td>';
															}
															return dOut;
														}
													}, 
													{
														data : 'number'
													},
													{
														data : 'unit'
													},
													{
														data : 'costPrice'
													},
													{
														data : 'unitPrice'
													}, 

													{
														data : 'power'
													}, {
														data : 'flowMaterial'
													}, {
														data : 'transMedia'
													}, {
														data : 'viscosity'
													}, {
														data : 'flux'
													}, {
														data : 'pumpLift'
													}, {
														data : 'temperature'
													}, {
														data : 'proportion'
													}, {
														data : 'inPressure'
													}, {
														data : 'effectiveNPSHA'
													}, {
														data : 'mustMPSHA'
													} ],
											"drawCallback" : function(oSettings) {
												var k = 0;
												var total = oSettings.aiDisplay.length
														+ oSettings._iDisplayStart;
												for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
													$(
															'td:eq(0)',
															oSettings.aoData[oSettings.aiDisplay[k]].nTr)
															.text(i + 1);
													k++;
												}

											}
										});
					});
	// 泵 添加按钮
	jQuery('.addMainBtn').on(
			"click",
			function() {
				if (jQuery("#foreignTradeInfo")
						&& !jQuery("#foreignTradeInfo").Validform({
							tiptype : 3,
							showAllError : true
						}).check(false)) {
					return;
				}
				;
				jQuery("#mainDeviceId").val('');
				jQuery("#productName").val('');
				jQuery("#productType").val('');
				jQuery("#productModel").val('');
				jQuery("#number").val('');
				jQuery("#unitPrice").val('');
				jQuery("#costPrice").val('');
				jQuery("#power").val('');
				jQuery("#viscosity").val('');
				jQuery("#flowMaterial").val('');
				jQuery("#transMedia").val('');
				jQuery("#proportion").val('');
				jQuery("#NPSHA").val('');
				jQuery("#flux").val('');
				jQuery("#temperature").val('');
				jQuery("#MPSHA").val('');
				jQuery("#pumpLift").val('');
				jQuery("#inPressure").val('');
				jQuery("#reduceNumber").val('');
				jQuery("#startDate").val('');
				jQuery("#endDate").val('');
				nowData.nowDataId = '';
				inDeviceData.quoteDeviceId = '';
				nowDataTable.draw();
				inDeviceTable.draw();
				jQuery("#mainDeviceModal").modal('show');
			});
	// 编辑泵
	jQuery(".editMainBtn").on(
			'click',
			function() {
				var selects = getSelect("#mainDeviceTable", 1);
				if (selects.length > 1) {
					$.springLemonDialog({
						content : '一次只能编辑一条记录',// 确认文本
						clickButton : function(sender, modal, index) {// 按钮事件处理
							$(this).closeDialog(modal);
						}
					});
				} else if (selects.length == 0) {
					$.springLemonDialog({
						content : '请选择要编辑的记录',// 确认文本
						clickButton : function(sender, modal, index) {// 按钮事件处理
							$(this).closeDialog(modal);
						}
					});
				} else if (selects.length == 1) {
					if (selects[0].linkDeviceId == null) {
						var id = selects[0].id;
						nowData.nowDataId = id;
						inDeviceData.quoteDeviceId = id;
						nowDataTable.draw();
						inDeviceTable.draw();
						jQuery("#mainDeviceId").val(id);
						jQuery("#maincreateTime").val(selects[0].createTime);
						jQuery("#productName").val(selects[0].productName);
						jQuery("#productType").val(selects[0].productType);
						jQuery("#productModel").val(selects[0].productModel);
						jQuery("#number").val(selects[0].number);
						jQuery("#deviceUnit").val(selects[0].unit);
						jQuery("#unitPrice").val(selects[0].unitPrice);
						jQuery("#costPrice").val(selects[0].costPrice);
						jQuery("#power").val(selects[0].power);
						jQuery("#viscosity").val(selects[0].viscosity);
						jQuery("#flowMaterial").val(selects[0].flowMaterial);
						jQuery("#transMedia").val(selects[0].transMedia);
						jQuery("#proportion").val(selects[0].proportion);
						jQuery("#NPSHA").val(selects[0].effectiveNPSHA);
						jQuery("#flux").val(selects[0].flux);
						jQuery("#temperature").val(selects[0].temperature);
						jQuery("#MPSHA").val(selects[0].mustMPSHA);
						jQuery("#pumpLift").val(selects[0].pumpLift);
						jQuery("#inPressure").val(selects[0].inPressure);
						jQuery("#inventoryState")
								.val(selects[0].inventoryState);
					} else {
						var url = window.rootPath
								+ '/ui/quote-foreign/getEditQuoteDevice'
								+ "?quoteDeviceId=" + selects[0].linkDeviceId;
						jQuery.ajax({
							type : 'get',
							url : encodeURI(url),
							dataType : 'json',
							contentType : 'application/json;charset=utf-8',
							success : function(data) {
								var id = data.quoteDevice.id;
								nowData.nowDataId = id;
								inDeviceData.quoteDeviceId = id;
								nowDataTable.draw();
								inDeviceTable.draw();
								jQuery("#mainDeviceId").val(id);
								jQuery("#maincreateTime").val(data.quoteDevice.createTime);
								jQuery("#productName").val(data.quoteDevice.productName);
								jQuery("#productType").val(data.quoteDevice.productType);
								jQuery("#productModel").val(data.quoteDevice.productModel);
								jQuery("#number").val(data.quoteDevice.number);
								jQuery("#deviceUnit").val(data.quoteDevice.unit);
								jQuery("#unitPrice").val(data.quoteDevice.unitPrice);
								jQuery("#costPrice").val(data.quoteDevice.costPrice);
								jQuery("#power").val(data.quoteDevice.power);
								jQuery("#viscosity").val(data.quoteDevice.viscosity);
								jQuery("#flowMaterial").val(data.quoteDevice.flowMaterial);
								jQuery("#transMedia").val(data.quoteDevice.transMedia);
								jQuery("#proportion").val(data.quoteDevice.proportion);
								jQuery("#NPSHA").val(data.quoteDevice.effectiveNPSHA);
								jQuery("#flux").val(data.quoteDevice.flux);
								jQuery("#temperature").val(data.quoteDevice.temperature);
								jQuery("#MPSHA").val(data.quoteDevice.mustMPSHA);
								jQuery("#pumpLift").val(data.quoteDevice.pumpLift);
								jQuery("#inPressure").val(data.quoteDevice.inPressure);
								jQuery("#inventoryState").val(data.quoteDevice.inventoryState);
							}
						});
					}
					jQuery("#startDate").val('');
					jQuery("#endDate").val('');
					jQuery("#reduceNumber").val('');
					jQuery("#mainDeviceModal").modal('show');

				}

			});
	// 删除泵
	jQuery(".delMainBtn")
			.on('click',function() {
						var selects = getSelect("#mainDeviceTable", 1);
						if (selects.length == 0) {
							$.springLemonDialog({
								content : '请选择删除的记录',// 确认文本
								clickButton : function(sender, modal, index) {// 按钮事件处理
									$(this).closeDialog(modal);
								}
							});
						} else {
							var ids = selects[0].id;
							for (var i = 1; i < selects.length; i++) {
								ids += ',' + selects[i].id;
							}
							var url = window.rootPath
									+ "/ui/quote-foreign/delMainDevice"
									+ "?ids=" + ids;
							$
									.springLemonDialog({
										content : '确认删除' + selects.length
												+ '条记录？',// 确认文本
										clickButton : function(sender, modal,
												index) {// 按钮事件处理
											if (index == 0) {
												jQuery(".btn").attr("disabled",
														"disable");
												jQuery
														.ajax({
															url : encodeURI(url),
															cache : false,
															type : "get",
															dataType : "json",
															contentType : "application/json;charset=utf-8",// 解决返回数据中的中文乱码问题
															success : function(data) {
																serverTable.draw();
																productSum();
																jQuery(".btn")
																		.removeAttr(
																				"disabled");
															}
														});
											}
											$(this).closeDialog(modal);
										}
									});
						}

					});

	// 泵保存按钮
	jQuery(".saveMainBtn").on("click", function() {
		if (jQuery("#mainDeviceForm") && !jQuery("#mainDeviceForm").Validform({
			tiptype : 3,
			showAllError : true
		}).check(false)) {
			return;
		}
		var quoteForeignId = jQuery("#id").val();
		if (quoteForeignId == '') {
			$.springLemonDialog({
				content : '将会同时保存价格单，是否确认保存？',// 确认文本
				clickButton : function(sender, modal, index) {// 按钮事件处理
					if (index == 0) {
						saveForeignQuote(2);
					}
					$(this).closeDialog(modal);
				}
			});
		} else if (quoteForeignId != '') {
			savePump(quoteForeignId);
		}
	});

	// ////////////////////// 其他 //////////////////////////
	// 其他table
	var serverData1 = {};
	var serverTable1;
	serverData1.quoteForeignId = jQuery("#id").val();
	jQuery(document)
			.ready(
					function() {
						serverTable1 = jQuery('#otherTable')
								.DataTable(
										{
											"serverSide" : true,
											"ordering" : false,
											"ajax" : {
												"dataType" : "json",
												"type" : "get",
												"cache" : false,
												"url" : window.rootPath
														+ '/ui/quote-foreign/getOtherpage',
												"data" : function(d) {
													return $.extend({}, d,
															serverData1);
												}
											},
											columns : [
													{
														data : null,
														defaultContent : ""
													},
													{
														data : null,
														defaultContent : "",
														render : function(data,
																type, full,
																meta) {
															var id = data.id;
															var operate = '<input type="checkbox" class="checkchild1">';
															return operate;

														}
													}, {
														data : 'deviceName'
													}, {
														data : 'type'
													}, {
														data : 'material'
													}, {
														data : 'unit'
													},
													{
														data : 'amount'
													}, 
													{
														data : 'costPrice'
													}, 
													{
														data : 'price'
													} 
												],
											"drawCallback" : function(oSettings) {
												var k = 0;
												var total = oSettings.aiDisplay.length
														+ oSettings._iDisplayStart;
												for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
													$(
															'td:eq(0)',
															oSettings.aoData[oSettings.aiDisplay[k]].nTr)
															.text(i + 1);
													k++;
												}
											}
										});

					});
	// 其他编辑
	jQuery(".editOtherBtn").on('click', function() {
		var selects = getSelect("#otherTable", 1);
		if (selects.length > 1) {
			$.springLemonDialog({
				content : '一次只能编辑一条记录',// 确认文本
				clickButton : function(sender, modal, index) {// 按钮事件处理
					$(this).closeDialog(modal);
				}
			});
		} else if (selects.length == 0) {
			$.springLemonDialog({
				content : '请选择要编辑的记录',// 确认文本
				clickButton : function(sender, modal, index) {// 按钮事件处理
					$(this).closeDialog(modal);
				}
			});
		} else if (selects.length == 1) {
			var id = selects[0].id;
			jQuery("#otherId").val(id);
			jQuery("#othercreateTime").val(selects[0].createTime);
			jQuery("#deviceName").val(selects[0].deviceName);
			jQuery("#type").val(selects[0].type);
			jQuery("#material").val(selects[0].material);
			jQuery("#unit").val(selects[0].unit);
			jQuery("#amount").val(selects[0].amount);
			jQuery("#price").val(selects[0].price);
			jQuery("#replacePrice").val(selects[0].costPrice);
			jQuery("#otherDeviceModal").modal("show");
		}
	});

	// 其他删除
	jQuery(".delOtherBtn")
			.on(
					'click',
					function() {
						var selects = getSelect("#otherTable", 1);
						if (selects.length == 0) {
							$.springLemonDialog({
								content : '请选择删除的记录',// 确认文本
								clickButton : function(sender, modal, index) {// 按钮事件处理
									$(this).closeDialog(modal);
								}
							});
						} else {
							var ids = selects[0].id;
							for (var i = 1; i < selects.length; i++) {
								ids += ',' + selects[i].id;
							}
							var url = window.rootPath
									+ "/ui/quote-foreign/delOtherDevice"
									+ "?ids=" + ids;
							$
									.springLemonDialog({
										content : '确认删除' + selects.length
												+ '条记录？',// 确认文本
										clickButton : function(sender, modal,
												index) {// 按钮事件处理
											if (index == 0) {
												jQuery(".btn").attr("disabled",
														true);
												jQuery
														.ajax({
															url : encodeURI(url),
															cache : false,
															type : "get",
															dataType : "json",
															contentType : "application/json;charset=utf-8",// 解决返回数据中的中文乱码问题
															success : function(
																	data) {
																serverTable1
																		.draw(false);
																serverTable2.draw(false); 
																productSum();
																jQuery(".btn")
																		.attr(
																				"disabled",
																				false);
															}
														});
											}
											$(this).closeDialog(modal);
										}
									});
						}
					});

	// 其他 添加按钮
	jQuery(".addOtherBtn").on(
			'click',
			function() {
				if (jQuery("#foreignTradeInfo")
						&& !jQuery("#foreignTradeInfo").Validform({
							tiptype : 3,
							showAllError : true
						}).check(false)) {
					return;
				}
				;
				jQuery("#otherId").val('');
				jQuery("#deviceName").val('');
				jQuery("#type").val('');
				jQuery("#material").val('');
				// jQuery("#unit").val('');
				jQuery("#amount").val('');
				jQuery("#price").val('');
				jQuery("#replacePrice").val('');
				jQuery("#otherDeviceModal").modal("show");
			});

	// 其他保存按钮
	jQuery(".saveOtherBtn").on(
			"click",
			function() {
				var quoteForeignId = jQuery("#id").val();
				if (jQuery("#otherDeviceForm")
						&& !jQuery("#otherDeviceForm").Validform({
							tiptype : 3,
							showAllError : true
						}).check(false)) {
					return;
				}
				if (quoteForeignId == '') {
					$.springLemonDialog({
						content : '将会同时保存价格单，是否确认保存？',// 确认文本
						clickButton : function(sender, modal, index) {// 按钮事件处理
							if (index == 0) {
								saveForeignQuote(3);
							}
							$(this).closeDialog(modal);
						}
					});
				} else if (quoteForeignId != '') {
					saveOther(quoteForeignId);
				}
			});

	// /////////////////////////// 泵添加弹窗 //////////////////////////////////
	// 弹窗中当前设备信息Table
	var nowData = {};
	var nowDataTable;
	var nowQuoteDevice;
	jQuery(document)
			.ready(
					function() {
						nowDataTable = jQuery('#nowDataTable')
								.DataTable(
										{
											"serverSide" : true,
											"ordering" : false,
											"ajax" : {
												"dataType" : "json",
												"type" : "get",
												"cache" : false,
												"url" : window.rootPath
														+ '/ui/quote-foreign/getnowDatapage',
												"data" : function(d) {
													return $.extend({}, d,
															nowData);
												}
											},
											columns : [
													{
														data : null,
														render : function(data,
																type, full,
																meta) {
															nowQuoteDevice = data;
														}
													}, {
														data : 'productName'
													}, {
														data : 'productType'
													}, {
														data : 'productModel'
													}, {
														data : 'costPrice'
													}, {
														data : 'unitPrice'
													}, {
														data : 'number'
													},{
														data : 'unit'
													},

													{
														data : 'power'
													}, {
														data : 'flowMaterial'
													}, {
														data : 'transMedia'
													}, {
														data : 'viscosity'
													}, {
														data : 'flux'
													}, {
														data : 'pumpLift'
													}, {
														data : 'temperature'
													}, {
														data : 'proportion'
													}, {
														data : 'inPressure'
													}, {
														data : 'effectiveNPSHA'
													}, {
														data : 'mustMPSHA'
													} ],
											"drawCallback" : function(oSettings) {
												var k = 0;
												var total = oSettings.aiDisplay.length
														+ oSettings._iDisplayStart;
												for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
													$(
															'td:eq(0)',
															oSettings.aoData[oSettings.aiDisplay[k]].nTr)
															.text(i + 1);
													k++;
												}
											}
										});
					});

	// 弹窗中已替换设备table
	var inDeviceData = {};
	var inDeviceTable;
	jQuery(document)
			.ready(
					function() {
						inDeviceTable = jQuery('#inDeviceTable')
								.DataTable(
										{
											"serverSide" : true,
											"ordering" : false,
											"ajax" : {
												"dataType" : "json",
												"type" : "get",
												"cache" : false,
												"url" : window.rootPath
														+ '/ui/inventoryReduce/getIsReplacePage',
												"data" : function(d) {
													return $.extend({}, d,
															inDeviceData);
												}
											},
											columns : [
													{
														data : null
													},
													{
														data : null,
														defaultContent : "",
														render : function(data,
																type, full,
																meta) {
															var operate = '<button type="button" class="btn btn-info btn-sm returnIn">还原</button>';
															return operate;
														}
													}, {
														data : 'name'
													}, {
														data : 'productType'
													},

													{
														data : 'figureNum'
													}, 
													{
														data : 'costPrice'
													}, 
													{
														data : 'unitPrice'
													}, 
													{
														data : 'number'
													}, 
													{
														data : 'unit'
													},
													{
														data : 'power'
													}, {
														data : 'flowMaterial'
													}, {
														data : 'transMedia'
													}, {
														data : 'viscosity'
													}, {
														data : 'flux'
													}, {
														data : 'pumpLift'
													}, {
														data : 'temperature'
													}, {
														data : 'proportion'
													}, {
														data : 'inPressure'
													}, {
														data : 'effectiveNPSHA'
													}, {
														data : 'mustMPSHA'
													} ],
											"drawCallback" : function(oSettings) {
												var k = 0;
												var total = oSettings.aiDisplay.length
														+ oSettings._iDisplayStart;
												for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
													$(
															'td:eq(0)',
															oSettings.aoData[oSettings.aiDisplay[k]].nTr)
															.text(i + 1);
													k++;
												}
												inDeviceTable
														.off('click', 'tr');
												inDeviceTable
														.on(
																'click',
																'tr',
																function(event) {
																	event = event
																			|| window.event;
																	var target = event.target
																			|| event.scrElement;
																	var data = inDeviceTable
																			.row(
																					this)
																			.data();
																	if (target.className
																			.indexOf('returnIn') != -1) {
																		returnInventory(data);
																	}
																	return;
																});
											}
										});
						// ////还原按钮
						var returnInventory = function(data) {
							var inventoryDullId = data.inventoryDullId;
							var number = data.number;
							var quoteDeviceId = data.quoteDevice.id;
							var url = window.rootPath
									+ '/ui/inventoryDull/returnInventory'
									+ "?inventoryDullId=" + inventoryDullId
									+ "&number=" + number + "&quoteDeviceId="
									+ quoteDeviceId;
							jQuery.ajax({
								url : encodeURI(url),
								type : 'post',
								dataType : 'json',
								contentType : 'application/json;charset=utf-8',
								success : function() {
									availableTable.draw(false);
									serverTable.draw(false);
								}
							});
							var url1 = window.rootPath
									+ "/api/inventoryReduces/" + data.id;
							jQuery.ajax({
								url : encodeURI(url1),
								cache : false,
								type : "delete",
								dataType : "json",
								success : function(data) {	
									inDeviceTable.draw(false);
								}
							});
							var d2 = {
								"inventoryState" : "0"
							}
							var url2 = window.rootPath + '/api/quoteDevices/'
									+ data.quoteDevice.id;
							jQuery.ajax({
								url : encodeURI(url2),
								type : 'patch',
								data : JSON.stringify(d2),
								dataType : 'json',
								contentType : 'application/json;charset=utf-8',
								success : function() {
									serverTable.draw(false);
									nowDataTable.draw(false);
								}

							});
						}

					});

	// 弹窗中可替换设备table
	var availableData = {};
	var availableTable;
	jQuery(document)
			.ready(
					function() {
						availableTable = jQuery('#availableTable')
								.DataTable(
										{
											"serverSide" : true,
											"ordering" : false,
											"ajax" : {
												"dataType" : "json",
												"type" : "get",
												"cache" : false,
												"url" : window.rootPath
														+ '/ui/inventoryDull/getavailablePage',
												"data" : function(d) {
													return $.extend({}, d,
															availableData);
												}
											},
											columns : [
													{
														data : null
													},
													{
														data : null,
														defaultContent : "",
														render : function(data,
																type, full,
																meta) {
															var operate = '<button type="button" class="btn btn-info btn-sm replace">替换</button>';
															return operate;
														}
													}, {
														data : "name"
													}, {
														data : "figureNum"
													}, {
														data : "material"
													}, {
														data : "usableNum"
													} ],
											"drawCallback" : function(oSettings) {
												var k = 0;
												var total = oSettings.aiDisplay.length
														+ oSettings._iDisplayStart;
												for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
													$(
															'td:eq(0)',
															oSettings.aoData[oSettings.aiDisplay[k]].nTr)
															.text(i + 1);
													k++;
												}
												availableTable.off('click',
														'tr');
												availableTable
														.on(
																'click',
																'tr',
																function(event) {
																	event = event|| window.event;
																	var target = event.target|| event.scrElement;
																	var data = availableTable.row(
																					this)
																			.data();
																	if (target.className
																			.indexOf('replace') != -1) {

																		replaceDull(data);
																	}

																	return;
																});
											}
										});
						// 替换
						var replaceDull = function(data) {
							var nowquoteDeviceId = nowData.nowDataId;
							if (nowquoteDeviceId == '') {
								$
										.springLemonDialog({
											content : "请先保存设备信息",// 确认文本
											clickButton : function(sender,
													modal, index) {
												$(this).closeDialog(modal);
											}
										});
							}

							else {
								if (nowQuoteDevice.inventoryState == '1') {
									$.springLemonDialog({
										content : "已经对该设备进行了降库，不能再次降库",// 确认文本
										clickButton : function(sender, modal,
												index) {
											$(this).closeDialog(modal);
										}
									});
								} else {
									if (jQuery("#periodForm")
											&& !jQuery("#periodForm")
													.Validform({
														tiptype : 3,
														showAllError : true
													}).check(false)) {
										return;
									}
									var reduceNumber = jQuery("#reduceNumber")
											.val();
									if (reduceNumber > data.usableNum
											|| reduceNumber > nowQuoteDevice.number) {
										$.springLemonDialog({
											content : "占库数量不能大于设备数量和可替换数量",// 确认文本
											clickButton : function(sender,
													modal, index) {
												$(this).closeDialog(modal);
											}
										});
									} else {
										var startDate1 = jQuery("#startDate")
												.val();
										var endDate1 = jQuery("#endDate").val();
										var startDate = new Date(startDate1)
												.getTime();
										var endDate = new Date(endDate1)
												.getTime()
										if (startDate > endDate) {
											$.springLemonDialog({
												content : "占库周期开始时间不能大于结束时间",// 确认文本
												clickButton : function(sender,
														modal, index) {
													$(this).closeDialog(modal);
												}
											});
										} else {
											var d = {
												"usableNum" : data.usableNum
														- reduceNumber
											};
											var url = window.rootPath
													+ '/api/inventoryDulls/'
													+ data.id;
											jQuery(".btn").attr("disabled",
													"disabled");
											jQuery
													.ajax({
														url : encodeURI(url),
														type : 'patch',
														data : JSON
																.stringify(d),
														dataType : 'json',
														contentType : 'application/json;charset=utf-8',
														success : function() {
															availableTable
																	.draw(false);
														}

													});
											var d1 = {
												"name" : data.name,
												"material" : data.material,
												"productType" : nowQuoteDevice.productType,
												"figureNum" : data.figureNum,
												"number" : reduceNumber,
												"costPrice":nowQuoteDevice.costPrice,
												"unitPrice" : nowQuoteDevice.unitPrice,
												"power" : nowQuoteDevice.power,
												"flowMaterial" : nowQuoteDevice.flowMaterial,
												"transMedia" : nowQuoteDevice.transMedia,
												"viscosity" : nowQuoteDevice.viscosity,
												"flux" : nowQuoteDevice.flux,
												"pumpLift" : nowQuoteDevice.pumpLift,
												"temperature" : nowQuoteDevice.temperature,
												"proportion" : nowQuoteDevice.proportion,
												"inPressure" : nowQuoteDevice.inPressure,
												"effectiveNPSHA" : nowQuoteDevice.effectiveNPSHA,
												"mustMPSHA" : nowQuoteDevice.mustMPSHA,
												"inventoryDullId" : data.id,
												"startDate" : jQuery(
														"#startDate").val(),
												"endDate" : jQuery("#endDate")
														.val(),
												"user" : {
													"id" : jQuery("#userId")
															.val()
												},
												"quoteDevice" : {
													"id" : nowData.nowDataId
												}
											};

											var api = window.rootPath
													+ "/ui/inventoryReduce/save";
											jQuery
													.ajax({
														type : 'post',
														url : encodeURI(api),
														data : JSON
																.stringify(d1),
														dataType : 'json',
														contentType : 'application/json;charset=utf-8',
														success : function(data) {
															jQuery("#startDate")
																	.val('');
															jQuery("#endDate")
																	.val('');
															jQuery(
																	"#reduceNumber")
																	.val('');
															inDeviceTable
																	.draw(false);
														}
													});

											var d3 = {
												"createTime" : nowQuoteDevice.createTime,
												"productName" : data.name,
												"productType" : nowQuoteDevice.productType,
												"productModel" : data.figureNum,
												"number" : reduceNumber,
												"unitPrice" : nowQuoteDevice.unitPrice,
												"costPrice" : nowQuoteDevice.costPrice,
												"power" : nowQuoteDevice.power,
												"flowMaterial" : nowQuoteDevice.flowMaterial,
												"transMedia" : nowQuoteDevice.transMedia,
												"viscosity" : nowQuoteDevice.viscosity,
												"flux" : nowQuoteDevice.flux,
												"pumpLift" : nowQuoteDevice.pumpLift,
												"temperature" : nowQuoteDevice.temperature,
												"proportion" : nowQuoteDevice.proportion,
												"inPressure" : nowQuoteDevice.inPressure,
												"effectiveNPSHA" : nowQuoteDevice.effectiveNPSHA,
												"mustMPSHA" : nowQuoteDevice.mustMPSHA,
												"isInventory" : "1",
												"linkDeviceId" : nowquoteDeviceId,
												"quoteForeign" : {
													"id" : nowQuoteDevice.quoteForeign.id
												}
											};
											var url3 = window.rootPath
													+ "/ui/quote-foreign/saveMainDevice";
											jQuery
													.ajax({
														type : 'post',
														url : encodeURI(url3),
														data : JSON
																.stringify(d3),
														dataType : 'json',
														contentType : 'application/json;charset=utf-8',
														success : function(data) {
															inDeviceTable
																	.draw(false);
														}
													});

											var d4 = {
												"createTime" : nowQuoteDevice.createTime,
												"productName" : nowQuoteDevice.productName,
												"productType" : nowQuoteDevice.productType,
												"productModel" : nowQuoteDevice.productModel,
												"number" : nowQuoteDevice.number
														- reduceNumber,
												"unitPrice" : nowQuoteDevice.unitPrice,
												"costPrice" : nowQuoteDevice.costPrice,
												"power" : nowQuoteDevice.power,
												"flowMaterial" : nowQuoteDevice.flowMaterial,
												"transMedia" : nowQuoteDevice.transMedia,
												"viscosity" : nowQuoteDevice.viscosity,
												"flux" : nowQuoteDevice.flux,
												"pumpLift" : nowQuoteDevice.pumpLift,
												"temperature" : nowQuoteDevice.temperature,
												"proportion" : nowQuoteDevice.proportion,
												"inPressure" : nowQuoteDevice.inPressure,
												"effectiveNPSHA" : nowQuoteDevice.effectiveNPSHA,
												"mustMPSHA" : nowQuoteDevice.mustMPSHA,
												"isInventory" : "2",
												"linkDeviceId" : nowquoteDeviceId,
												"quoteForeign" : {
													"id" : nowQuoteDevice.quoteForeign.id
												}
											};
											jQuery
													.ajax({
														type : 'post',
														url : encodeURI(url3),
														data : JSON
																.stringify(d4),
														dataType : 'json',
														contentType : 'application/json;charset=utf-8',
														success : function(data) {
															inDeviceTable
																	.draw(false);
														}
													});

											var d2 = {
												"inventoryState" : "1"
											}
											var url2 = window.rootPath
													+ '/api/quoteDevices/'
													+ nowquoteDeviceId;
											jQuery
													.ajax({
														url : encodeURI(url2),
														type : 'patch',
														data : JSON
																.stringify(d2),
														dataType : 'json',
														contentType : 'application/json;charset=utf-8',
														success : function() {
															serverTable
																	.draw(false);
															nowDataTable.draw();
															jQuery(".btn")
																	.removeAttr(
																			"disabled");
														}

													});
										}
									}

								}
							}

						}

					});

	// 价格单保存按钮
	jQuery(".saveBtn").on(
			"click",
			function() {
				if (jQuery("#foreignTradeInfo")
						&& !jQuery("#foreignTradeInfo").Validform({
							tiptype : 3,
							showAllError : true
						}).check(false)) {
					return;
				}
				saveForeignQuote(1);
			});

	// ////////////////////////// 保存方法 ///////////////////////////////
	// 保存外贸价格单
	function saveForeignQuote(isreturn) {
		// isreturn==1,直接返回外贸价格单首页；isreturn==2在保存价格单和泵后留在当前页；isreturn==3在保存价格单和其他后留在当前页；isreturn==4在保存价格单后上传附件；isreturn==5保存价格单留在当前页；
		
		var id = jQuery("#id").val();
		var quotecreateTime = jQuery("#quotecreateTime").val();
		var createTime = new Date(quotecreateTime).getTime();
		var name = jQuery("#name").val();
		var memo = jQuery("#memo").val();
		var currency = jQuery("#currency").val();
		var costSum = jQuery("#costSum").val();
		var productSum = jQuery("#productSum").val();
		var productRatio = jQuery("#productRatio").val();
		var productOff = jQuery("#productOff").val();
		var packPrice = jQuery("#packPrice").val();
		var exportWay = jQuery("#exportWay").val();
		var packRatio = jQuery("#packRatio").val();
		var packOff = jQuery("#packOff").val();
		var sum = jQuery("#sum").val();
		var quoteExplain = jQuery("#quoteExplain").val();
		var customerId = jQuery("#customerId").val();
		var customerName = jQuery("#customerName").val();
		var deliveryDate = jQuery("#deliveryDate").val();
		var payment = jQuery("#payment").val();
		var validity = jQuery("#validity").val();
		var userId = jQuery("#userId").val();
		var url = window.rootPath + "/ui/quote-foreign/save";
		if (id == '') {
			var d = {
				"name" : name,
				"memo" : memo,
				"currency" : currency,
				"costSum":costSum,
				"productSum" : productSum,
				"productRatio" : productRatio,
				"productOff" : productOff,
				"packPrice" : packPrice,
				"exportWay" : exportWay,
				"packRatio" : packRatio,
				"packOff" : packOff,
				"sum" : sum,
				"customerId" : customerId,
				"customerName" : customerName,
				"deliveryDate" : deliveryDate,
				"payment" : payment,
				"validity" : validity,
				"quoteExplain" : quoteExplain,
				"user" : {
					"id" : userId
				}
			};
		} else {
			var d = {
				"id" : id,
				"createTime" : createTime,
				"name" : name,
				"memo" : memo,
				"currency" : currency,
				"costSum":costSum,
				"productSum" : productSum,
				"productRatio" : productRatio,
				"productOff" : productOff,
				"packPrice" : packPrice,
				"exportWay" : exportWay,
				"packRatio" : packRatio,
				"packOff" : packOff,
				"sum" : sum,
				"customerId" : customerId,
				"customerName" : customerName,
				"deliveryDate" : deliveryDate,
				"payment" : payment,
				"validity" : validity,
				"quoteExplain" : quoteExplain,
				"user" : {
					"id" : userId
				}
			};
		}
		jQuery(".btn").attr("disabled", true);
		jQuery.ajax({
			type : 'post',
			url : encodeURI(url),
			data : JSON.stringify(d),
			dataType : 'json',
			contentType : 'application/json;charset=utf-8',
			success : function(data) {
				if (isreturn == 1) {
					$.springLemonDialog({
						content : '保存成功',// 确认文本
						clickButton : function(sender, modal, index) {// 按钮事件处理
							$(this).closeDialog(modal);
						}
					});
					window.location = window.rootPath + "/ui/quote-foreign";
				} else if (isreturn == 2) {
					var quoteForeignId = data.quoteForeignId;
					var time = moment(data.createTime).format(
							"YYYY-MM-DD HH:mm:ss");
					jQuery("#id").val(quoteForeignId);
					jQuery("#quotecreateTime").val(time);
					serverData.quoteForeignId = quoteForeignId;
					serverData1.quoteForeignId = quoteForeignId;
					savePump(quoteForeignId);
				} else if (isreturn == 3) {
					var quoteForeignId = data.quoteForeignId;
					var time = moment(data.createTime).format(
							"YYYY-MM-DD HH:mm:ss");
					jQuery("#id").val(quoteForeignId);
					jQuery("#quotecreateTime").val(time);
					serverData.quoteForeignId = quoteForeignId;
					serverData1.quoteForeignId = quoteForeignId;
					saveOther(quoteForeignId);
				} else if (isreturn == 4) {
					var quoteForeignId = data.quoteForeignId;
					var time = moment(data.createTime).format(
							"YYYY-MM-DD HH:mm:ss");
					jQuery('#id').val(quoteForeignId);
					jQuery("#quotecreateTime").val(time);
					serverData.quoteForeignId = quoteForeignId;
					serverData1.quoteForeignId = quoteForeignId;
					fileUpload(quoteForeignId, "外贸价格单附件", null,
							'foreign-quote-ANum');
				}else if(isreturn == 5){
					;
				}
				
				jQuery(".btn").attr("disabled", false);
			}
		});
	}

	// 保存泵
	function savePump(quoteForeignId) {
		var url1 = window.rootPath + '/ui/quote-foreign/saveMainDevice';
		var id = jQuery("#mainDeviceId").val();
		var createTime = jQuery("#maincreateTime").val();
		var productName = jQuery("#productName").val();
		var productType = jQuery("#productType").val();
		var productModel = jQuery("#productModel").val();
		var number = jQuery("#number").val();
		var unit = jQuery("#deviceUnit").val();
		var costPrice = jQuery("#costPrice").val();
		var unitPrice = jQuery("#unitPrice").val();
		var power = jQuery("#power").val();
		var flowMaterial = jQuery("#flowMaterial").val();
		var transMedia = jQuery("#transMedia").val();
		var viscosity = jQuery("#viscosity").val();
		var flux = jQuery("#flux").val();
		var pumpLift = jQuery("#pumpLift").val();
		var temprature = jQuery("#temperature").val();
		var proportion = jQuery("#proportion").val();
		var inPressure = jQuery("#inPressure").val();
		var NPSHA = jQuery("#NPSHA").val();
		var MPSHA = jQuery("#MPSHA").val();
		var inventoryState = jQuery("#inventoryState").val();
		if (id == '') {
			var d = {
				"productName" : productName,
				"productType" : productType,
				"productModel" : productModel,
				"number" : number,
				"unit":unit,
				"unitPrice" : unitPrice,
				"costPrice" : costPrice,
				"power" : power,
				"flowMaterial" : flowMaterial,
				"transMedia" : transMedia,
				"viscosity" : viscosity,
				"inventoryState" : 0,
				"flux" : flux,
				"pumpLift" : pumpLift,
				"temperature" : temprature,
				"proportion" : proportion,
				"inPressure" : inPressure,
				"effectiveNPSHA" : NPSHA,
				"mustMPSHA" : MPSHA,
				"inventoryState" : "0",
				"quoteForeign" : {
					"id" : quoteForeignId
				}
			};
		} else {
			var d = {
				"id" : id,
				"createTime" : createTime,
				"productName" : productName,
				"productType" : productType,
				"productModel" : productModel,
				"number" : number,
				"unit":unit,
				"unitPrice" : unitPrice,
				"costPrice" : costPrice,
				"power" : power,
				"flowMaterial" : flowMaterial,
				"transMedia" : transMedia,
				"viscosity" : viscosity,
				"flux" : flux,
				"pumpLift" : pumpLift,
				"temperature" : temprature,
				"proportion" : proportion,
				"inPressure" : inPressure,
				"effectiveNPSHA" : NPSHA,
				"mustMPSHA" : MPSHA,
				"inventoryState" : inventoryState,
				"quoteForeign" : {
					"id" : quoteForeignId
				}
			};
		}
		jQuery(".btn").attr("disabled", "disabled");
		jQuery.ajax({
			type : 'post',
			url : encodeURI(url1),
			data : JSON.stringify(d),
			dataType : 'json',
			contentType : 'application/json;charset=utf-8',
			success : function(data) {
				nowData.nowDataId = data.nowData.id;
				inDeviceData.quoteDeviceId = nowData.nowDataId;
				serverTable.draw();
				nowDataTable.draw();
				availableTable.draw();
				inDeviceTable.draw();
				productSum();
				saveForeignQuote(5);
				jQuery("#productName").val('');
				jQuery("#productType").val('');
				jQuery("#productModel").val('');
				jQuery("#number").val('');
				jQuery("#unitPrice").val('');
				jQuery("#costPrice").val('');
				jQuery("#power").val('');
				jQuery("#viscosity").val('');
				jQuery("#flowMaterial").val('');
				jQuery("#transMedia").val('');
				jQuery("#proportion").val('');
				jQuery("#NPSHA").val('');
				jQuery("#flux").val('');
				jQuery("#temperature").val('');
				jQuery("#MPSHA").val('');
				jQuery("#pumpLift").val('');
				jQuery("#inPressure").val('');
				jQuery(".btn").removeAttr("disabled");
			}
		});
	}

	// 保存其他
	function saveOther(quoteForeignId) {
		var url2 = window.rootPath + '/ui/quote-foreign/saveOtherDevice';
		var otherId = jQuery("#otherId").val();
		var deviceName = jQuery('#deviceName').val();
		var type = jQuery('#type').val();
		var material = jQuery("#material").val();
		var unit = jQuery('#unit').val();
		var amount = jQuery('#amount').val();
		var replacePrice = jQuery('#replacePrice').val();
		var price = jQuery('#price').val();
		if (otherId == '') {
			var d = {
				"deviceName" : deviceName,
				"type" : type,
				"material" : material,
				"unit" : unit,
				"amount" : amount,
				"price" : price,
				"costPrice" : replacePrice,
				"quoteForeign" : {
					"id" : quoteForeignId
				}
			};
		} else {
			var createTime = jQuery("#othercreateTime").val();
			var d = {
				"id" : otherId,
				"createTime" : createTime,
				"deviceName" : deviceName,
				"type" : type,
				"material" : material,
				"unit" : unit,
				"amount" : amount,
				"price" : price,
				"costPrice" : replacePrice,
				"quoteForeign" : {
					"id" : quoteForeignId
				}
			};

		}
		jQuery(".btn").attr("disabled", true);
		jQuery.ajax({
			type : 'post',
			url : encodeURI(url2),
			data : JSON.stringify(d),
			dataType : 'json',
			contentType : 'application/json;charset=utf-8',
			success : function(data) {
				jQuery('#otherDeviceModal').modal('hide');
				serverTable1.draw();
				serverTable2.draw(); 
				productSum();
				jQuery(".btn").attr("disabled", false);
			}
		});

	}
	// /////////////////////// 计算价格 ///////////////////////////
	// /计算产品总价（总原价和总报价）

	var productSum = function() {
		var id = jQuery("#id").val();
		var url = window.rootPath + '/ui/quote-foreign/getQuoteDevice' + "?id="
				+ id;
		var url1 = window.rootPath + '/ui/quote-foreign/getQuoteReplacement'
				+ "?id=" + id;
		jQuery.ajax({
			type : 'get',
			url : encodeURI(url),
			dataType : 'json',
			contentType : 'application/json;charset=utf-8',
			success : function(data) {
				var quoteDevices = data.quoteDevices;
				var mainSum = 0;
				var costSum = 0;
				for (var n = 0; n < quoteDevices.length; n++) {
					var main = quoteDevices[n].number
							* quoteDevices[n].unitPrice;
					var cost = quoteDevices[n].number*quoteDevices[n].costPrice;
					mainSum += main;
					costSum += cost;
				}
				jQuery.ajax({
					type : 'get',
					url : encodeURI(url1),
					dataType : 'json',
					contentType : 'application/json;charset=utf-8',
					success : function(data) {
						var quoteReplacements = data.quoteReplacements;
						var otherSum = 0;
						var costOtherSum = 0;
						for (var n = 0; n < quoteReplacements.length; n++) {
							var other = quoteReplacements[n].amount
									* quoteReplacements[n].price;
							var costOther = quoteReplacements[n].amount*quoteReplacements[n].costPrice;
							costOtherSum +=costOther;
							otherSum += other;
						}
						var sum = mainSum + otherSum;
						var allSum = costSum + costOtherSum;
						jQuery("#productSum").val(sum);
						jQuery("#costSum").val(allSum);
						productRatio();
						productOff();
						coculateSum();
						saveForeignQuote(5);
					}
				});
			}
		});
	}


	//计算浮动比例
	jQuery("#productRatio").blur(function(){
		productRatio();
	})
	var productRatio=function(){
		var  productSum = jQuery("#productSum").val();
		var  costSum=jQuery("#costSum").val();
		if (!isNaN(Number(productSum)) && !isNaN(Number(costSum))) {
			jQuery("#productRatio").val((( productSum-costSum)/costSum*100).toFixed(2));
		}
	}
	// 计算产品浮动金额
	jQuery('#productOff').blur(function() {
		productOff();
	});
	var productOff = function() {
		var productSum = jQuery("#productSum").val();
		var  costSum=jQuery("#costSum").val();
		//var productRatio = jQuery("#productRatio").val() / 100;
		if (!isNaN(Number(productSum)) && !isNaN(Number(costSum))) {
			jQuery("#productOff").val((productSum-costSum).toFixed(2));
		}
	}
	// 包装费
	jQuery('#packPrice').blur(function() {
		packOff();
		coculateSum();
	});
	jQuery('#packRatio').blur(function() {
		packOff();
		coculateSum();
	});
	var packOff = function() {
		var packPrice = jQuery("#packPrice").val();
		var packRatio = jQuery("#packRatio").val() / 100;
		if (!isNaN(Number(packPrice)) && !isNaN(Number(packRatio))) {
			jQuery("#packOff").val((packPrice * packRatio).toFixed(2));
		}

	}

	// 计算总价
	var coculateSum = function() {
		var productSum =jQuery("#productSum").val();
		var packPrice = jQuery("#packPrice").val();
		var packOff = jQuery("#packOff").val();
		if (!isNaN(Number(productSum)) &&!isNaN(Number(packPrice))
				&& !isNaN(Number(packOff))) {
			var pack = Number(packPrice)+Number(packOff);
			var sum=Number(productSum) +  pack;
			jQuery("#sum").val(sum.toFixed(2));
		}
	}
	// 总价计算折扣比列
//	jQuery("#sum")
//			.blur(
//					function() {
//						var sum = jQuery("#sum").val();
//						if (sum == '')
//							sum = 0;
//						var productSum = jQuery("#productSum").val();
//						if (productSum == '')
//							productSum = 0;
//						var packPrice = jQuery("#packPrice").val();
//						if (packPrice == '')
//							packPrice = 0;
//						var packOff = jQuery("#packOff").val();
//						if (packOff == '')
//							packOff = 0;
//						if (!isNaN(Number(sum)) && !isNaN(Number(productSum))
//								&& !isNaN(Number(packPrice))
//								&& !isNaN(Number(packOff))) {
//							var sum1 = parseFloat(sum) + parseFloat(packOff);
//							var totalPrice = parseFloat(productSum)
//									+ parseFloat(packPrice);
//							var productOff = totalPrice - sum1;
//							jQuery("#productOff").val(productOff.toFixed(1));
//							if (productSum != 0) {
//								var productRatio = productOff / productSum
//										* 100;
//								jQuery("#productRatio").val(
//										productRatio.toFixed(1));
//							} else
//								jQuery("#productRatio").val(0);
//						}
//					});
	// 弹窗中可替换设备查询
	jQuery(".searchDull").on('click', function() {
		availableData.key = jQuery("#dullKey").val();
		availableTable.draw();
	});
	// 撤销按钮
	jQuery(".resetDull").on('click', function() {
		jQuery("#dullKey").val('');
		availableData.key = '';
		availableTable.draw();
	});
	// /////泵列表中的全选
	$("#checkAll").click(function() {
		var check = $(this).prop("checked");
		$(".checkchild").prop("checked", check);
	});
	// ////其他列表中的全选
	$("#checkAll1").click(function() {
		var check = $(this).prop("checked");
		$(".checkchild1").prop("checked", check);
	});

	// 上传附件
	jQuery(".upload").on(
			'click',
			function() {
				var quoteForeignId = jQuery("#id").val();
				if (quoteForeignId == '') {
					if (jQuery("#foreignTradeInfo")
							&& !jQuery("#foreignTradeInfo").Validform({
								tiptype : 3,
								showAllError : true
							}).check(false)) {
						return;
					}                                           
					;
					$.springLemonDialog({
						content : '将保存价格单，是否继续',// 确认文本
						clickButton : function(sender, modal, index) {// 按钮事件处理
							if (index == 0) {
								saveForeignQuote(4);
							}
							$(this).closeDialog(modal);
						}
					});
				} else {
					fileUpload(quoteForeignId, "外贸价格单附件", null,
							'foreign-quote-ANum');
				}
			});     

	// 下载附件
	jQuery(".download").on('click', function() {
		var quoteForeignId = jQuery("#id").val();
		filedown(quoteForeignId, '外贸价格单附件', 1);
	});
	// //获附件数量
	var quoteForeignId = jQuery("#id").val();
	var numId = 'foreign-quote-ANum';
	if (quoteForeignId != '') {
		showANum(quoteForeignId, '外贸价格单附件', numId);
	}

});
